package cn.wzptsoft.tinymallbe.service;

import cn.wzptsoft.tinymallbe.entity.Category;
import cn.wzptsoft.tinymallbe.entity.Sku;
import cn.wzptsoft.tinymallbe.entity.Spu;
import cn.wzptsoft.tinymallbe.repository.CategoryRepository;
import cn.wzptsoft.tinymallbe.repository.SpuRepository;
import cn.wzptsoft.tinymallbe.vo.CategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class SpuService {
    @Autowired
    private SpuRepository spuRepository;

    @Autowired
    private CategoryRepository categoryRepository;

//    商品列表分页查询
    public Page<Spu> getSpuByPage(int pageNum, Integer size) {
       Pageable page= PageRequest.of(pageNum,size, Sort.by("createTime").descending());
        Page<Spu> result = spuRepository.findAll(page);
        return result;
    }

    public Optional<Spu> getSpu(Long id) {
        Optional<Spu> byId = spuRepository.findById(id);
        return byId;
    }

    public Page<Spu> getByCategory(Long categoryId, Boolean isRoot, int pageNum, Integer size) {
        PageRequest page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
        Page<Spu> pageResult;
//        如果不是根分类，直接以categoryId为条件询查
        if (!isRoot){
            pageResult=this.spuRepository.findByCategoryId(categoryId,page);
        }else {
//        如果是根分类，先查出根分类的二级分类，在以二级分类为条件进行询查
            List<Category> subCategorys=categoryRepository.findByParentId(categoryId);
           List<Long> subCategoryIds = subCategorys.stream()
                   .map(Category::getId)
                   .collect(Collectors.toList());
           pageResult= spuRepository.findByCategoryIdIn(subCategoryIds,page);
        }
        return pageResult;
    }



}
